package com.zzu.view.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.king.zxing.util.CodeUtils;
import com.zzu.R;
import com.zzu.model.bean.PackageItem;
import com.zzu.model.bean.PackageRoute;
import com.zzu.model.bean.User;
import com.zzu.presenter.impl.PackagePresenterImpl;
import com.zzu.utils.AppStorage;
import com.zzu.view.view.PackageQueryView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ExpressInfoFragment extends Fragment implements View.OnClickListener {

    public static final String PACKAGE_ID = "package_id";
    public static final String NOW_ADDRESS = "now_address";

    private static final String TAG = ExpressInfoFragment.class.getName();

    @BindView(R.id.iv_express_zxing)
    ImageView iv_express_zxing;
    @BindView(R.id.tv_express_packageId)
    TextView tvExpressPackageId;
    @BindView(R.id.tv_express_sender)
    TextView tvExpressSender;
    @BindView(R.id.tv_express_senderTel)
    TextView tvExpressSenderTel;
    @BindView(R.id.tv_express_senderAddr)
    TextView tvExpressSenderAddr;
    @BindView(R.id.tv_express_receiver)
    TextView tvExpressReceiver;
    @BindView(R.id.tv_express_receiverTel)
    TextView tvExpressReceiverTel;
    @BindView(R.id.tv_express_receiverAddr)
    TextView tvExpressReceiverAddr;
    @BindView(R.id.tv_express_status)
    TextView tvExpressStatus;
    @BindView(R.id.tv_express_update_time)
    TextView tvExpressUpdateTime;
    //改变包裹状态的按钮
    @BindView(R.id.bt_express_change_status)
    Button btExpressChangeStatus;

    Context mContext = null;
    private String packageId = "1234567891234";
    //包裹的信息
    PackageItem packageItem = null;

    //包裹的状态
    private int status = 0;
    /**
     * 按钮的状态
     * 0:揽收
     * 1:发货
     * 2:打包拆包
     * 3:派送
     * 4:快递送达
     * 5:已签收，此时不能点击，隐藏改按钮
     */
    private int buttonStatus = 0;
    //包裹的编号
    private String id = "1234567891234";

    //用户信息
    private User mUser = AppStorage.getUser();

    //当前包裹的位置信息
    private String nowAddress = "河南省郑州市中原区";

    //Map快递状态的map
    public static Map<Integer,String> NumToTextStatus = new HashMap<>();
    public static Map<Integer,String> NumToBtnStatus = new HashMap<>();
    static {
        NumToTextStatus.put(0,"待揽收");
        NumToTextStatus.put(1,"已揽收");
        NumToTextStatus.put(2,"已发货");
        NumToTextStatus.put(3,"运输中");
        NumToTextStatus.put(4,"派送中");
        NumToTextStatus.put(5,"已签收");

        NumToBtnStatus.put(0,"揽收");
        NumToBtnStatus.put(1,"发货");
        NumToBtnStatus.put(2,"打包拆包");
        NumToBtnStatus.put(3,"派送");
        NumToBtnStatus.put(4,"快递送达");
        NumToBtnStatus.put(5,"已签收");
    }

    public ExpressInfoFragment() {
        // Required empty public constructor
    }

    public static ExpressInfoFragment newInstance(String packageId,String nowAddress) {
        ExpressInfoFragment fragment = new ExpressInfoFragment();
        Bundle args = new Bundle();
        //设置包裹id和包裹当前的位置
        args.putString(PACKAGE_ID, packageId);
        args.putString(NOW_ADDRESS, nowAddress);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        if (getArguments() != null) {
            //获取到包裹的id和包裹当前的地址
            packageId = getArguments().getString(PACKAGE_ID);
            nowAddress = getArguments().getString(NOW_ADDRESS);
            Log.i(TAG,"获取到的包裹id："+packageId+",现住址："+nowAddress);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_expressinfo, container, false);
        //进行组件的绑定
        ButterKnife.bind(this,view);
        initData();
        initListener();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    //初始化数据
    private void initData() {
        //获取到包裹id之后进行数据的查询
        new PackagePresenterImpl(mContext,new PackageQueryView<PackageItem>() {
            @Override
            public void getDates(PackageItem data) {
                if(data == null){
                    Log.i(TAG,"没有获取到数据");
                    return;
                }
                //设置包裹当前扫描的位置
                packageItem = data;
                packageItem.setNowAddress(nowAddress);
                Log.i(TAG,"包裹id为"+packageId+"信息为："+data.toString());
                status = packageItem.getStatus();
                setDataForView(packageItem);
            }

            @Override
            public void getNoDate() {
                Log.i(TAG,"没有该订单信息");
                Toast.makeText(mContext, "对不起，没有该订单信息！！", Toast.LENGTH_LONG).show();
                return;
            }
        }).getPackageById(packageId);

    }

    /**
     * 进行包裹信息的设置
     * @param packageItem
     */
    private void setDataForView(PackageItem packageItem) {
        Log.i(TAG,"进行包裹信息的设置"+packageItem);
        //进行包裹信息的设置
        id = packageItem.getId();
        tvExpressPackageId.setText(packageItem.getId());

        //条形码的加载,如果当前包裹状态为0（未揽收）就不加载条形吗
        if(status != 0){
            //加载条形码
            //根据string生成bitmap（条形码）
            Bitmap bm = getBitmap();
            iv_express_zxing.setImageBitmap(bm);
        }
        tvExpressSender.setText(packageItem.getSender());
        tvExpressSenderTel.setText(packageItem.getSenderTel());
        tvExpressSenderAddr.setText(AppStorage.getRegionName(packageItem.getSourceNode())+packageItem.getSenderAddr());
        tvExpressReceiver.setText(packageItem.getReceiver());
        tvExpressReceiverTel.setText(packageItem.getReceiverTel());
        tvExpressReceiverAddr.setText(AppStorage.getRegionName(packageItem.getTargetNode())+packageItem.getReceiverAddr());
        tvExpressUpdateTime.setText(packageItem.getUpdateTime());
        //设置快递状态
        tvExpressStatus.setText(NumToTextStatus.get(status));

        //设置按钮的状态，计算出buttonStatus，通过NumToBtnStatus显示按钮状态
        changeButtonStatus();
        btExpressChangeStatus.setText(NumToBtnStatus.get(buttonStatus));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){

            case R.id.bt_express_change_status:
                //改变包裹状态的按钮
                changeStatus();
                break;
            default:
                break;
        }
    }

    private void changeButtonStatus() {
        //改变当前包裹的当前的状态
        switch (status){
            case 0:
                //显示为揽收
                buttonStatus = 0;
                break;
            case 1:
                //显示为发货
                buttonStatus = 1;
                break;
            case 2:
                buttonStatus = 2;
                break;
            case 3:
                //包裹的状态为3，且包裹当前的位置和目的地相同，则按钮为派送
                if(packageItem.getNowAddress().equals(AppStorage.getRegionName(packageItem.getTargetNode()))){
                    buttonStatus = 3;
                }else{
                    buttonStatus = 2;
                }
                break;
            case 4:
                //包裹状态为派送中，按钮为快递送达
                buttonStatus = 4;
                break;
            case 5:
                buttonStatus = 5;
            default:
                break;
        }

    }


    private void initListener() {

        //右下角改变包裹状态按钮的监听
        btExpressChangeStatus.setOnClickListener(this);
    }

    private void changeStatus() {
        //通过当前按钮的状态
        /**
         * 按钮的状态
         * 0:揽收
         * 1:发货
         * 2:打包拆包
         * 3:派送
         * 4:快递送达
         * 5:已签收，此时不能点击，隐藏改按钮
         */
        switch (buttonStatus){
            case 0:
                zeroToOne();
                break;
            case 1:
                //点击了发货按钮
                oneToTwo();
                break;
            case 2:
                //点击了打包拆包
                twoToThree();
                break;
            case 3:
                threeToFour();
                break;
            case 4:
                //点击了快递送达，将包裹的状态从4改成5
                fourToFive();
                break;
        }
    }


    /**
     * 提示框提示快递是否已送到用户手中，点击确认将包裹的状态改成5
     */
    private void fourToFive() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_textview, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setIcon(R.mipmap.ic_launcher).setTitle("提示")
                .setMessage("快递是否已送到用户手中？")
                .setView(dialogView)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.e(TAG,"点击了确定");
                        //点击了快递送达按钮，修改包裹的状态为5
                        PackageRoute packageRoute = new PackageRoute(id, mUser.getTransNodeId(), Long.parseLong(mUser.getId()), 5, 0.0, 0.0);
                        new PackagePresenterImpl(mContext,new PackageQueryView<Boolean>() {
                            @Override
                            public void getDates(Boolean result) {
                                if(result){
                                    Toast.makeText(mContext,"快递已送达",Toast.LENGTH_SHORT).show();
                                    initData();
                                }else{
                                    Toast.makeText(mContext,"服务器出现问题正在抢修中。。。",Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void getNoDate() {
                                Toast.makeText(mContext,"服务器出现问题正在抢修中。。。",Toast.LENGTH_SHORT).show();
                            }
                        }).updatePackageStatus(packageRoute);
                    }
                })
                .setNegativeButton("取消",new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.e(TAG,"点击了取消");
                        //没有其他操作
                    }
                })
                .create()
                .show();
    }

    /**
     * 点击了派送按钮，后台将包裹状态更新为4，提示管理员快递正在派送中
     */
    private void threeToFour() {
        //点击派送按钮
        PackageRoute packageRoute = new PackageRoute(id, mUser.getTransNodeId(), Long.parseLong(mUser.getId()), 4, 0.0, 0.0);
        //后台更新包裹状态数据。。。。。。。。
        new PackagePresenterImpl(mContext, new PackageQueryView<Boolean>() {
            @Override
            public void getDates(Boolean result) {
                if(result){
                    Toast.makeText(mContext,"包裹状态已更新，准备派送",Toast.LENGTH_SHORT).show();
                    initData();
//                    finish();
                }
            }

            @Override
            public void getNoDate() {

            }
        }).updatePackageStatus(packageRoute);
    }

    /**
     * 用户点击了打包拆包的按钮，根据快递的当前位置提示快递下一站站点
     * 弹出提示框，当前位置为，快递下一站为。。。。
     */
    private void twoToThree() {

        //快递下一站的站点
        String nextAddress = getNextAddress(packageItem);
        //弹出提示框
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_textview, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setIcon(R.mipmap.ic_launcher).setTitle("提示")
                .setMessage("当前站点是"+packageItem.getNowAddress()+",下一站站点为："+nextAddress+"运输站")
                .setView(dialogView)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //更改包裹状态为3
                        //点击了快递送达按钮，修改包裹的状态为5
                        PackageRoute packageRoute = new PackageRoute(id, mUser.getTransNodeId(), Long.parseLong(mUser.getId()), 3, 0.0, 0.0);
                        new PackagePresenterImpl(mContext,new PackageQueryView<Boolean>() {
                            @Override
                            public void getDates(Boolean result) {
                                if(result){
                                    Toast.makeText(mContext,"快递状态已更新",Toast.LENGTH_SHORT).show();
                                    initData();
                                }else{
                                    Toast.makeText(mContext,"服务器出现问题正在抢修中。。。",Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void getNoDate() {
                                Toast.makeText(mContext,"服务器出现问题正在抢修中。。。",Toast.LENGTH_SHORT).show();
                            }
                        }).updatePackageStatus(packageRoute);

                    }
                })
                .setNegativeButton("取消",new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.e(TAG,"点击了取消");
                    }
                })
                .create()
                .show();
    }


    /**
     * 点击了发货按钮
     */
    private void oneToTwo() {
        //点击发货按钮
        PackageRoute packageRoute = new PackageRoute(id, mUser.getTransNodeId(), Long.parseLong(mUser.getId()), 2, 0.0, 0.0);
        //后台更新包裹状态数据。。。。。。。。
        new PackagePresenterImpl(mContext,new PackageQueryView<Boolean>() {
            @Override
            public void getDates(Boolean result) {
                if(result){
                    Toast.makeText(mContext,"快递已发货",Toast.LENGTH_SHORT).show();
                    initData();
//                    try {
//                        Thread.sleep(300);
////                        finish();
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
                }else{
                    Toast.makeText(mContext,"服务器出现问题正在抢修中。。。",Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void getNoDate() {
                Toast.makeText(mContext,"服务器出现问题正在抢修中。。。",Toast.LENGTH_SHORT).show();
            }
        }).updatePackageStatus(packageRoute);
    }

    //当状态为0的时候点击揽收按钮，按钮改成发货，提示管理员已发货，并在主页面中加入条形码
    private void zeroToOne(){
        //点击完更改包裹状态，显示二维码。结束当前页面
        PackageRoute packageRoute = new PackageRoute(id, mUser.getTransNodeId(), Long.parseLong(mUser.getId()), 1, 0.0, 0.0);
        //后台更新包裹状态数据。。。。。。。。
        new PackagePresenterImpl(mContext,new PackageQueryView() {
            @Override
            public void getDates(Object datas) {

            }
            @Override
            public void getNoDate() {

            }
        }).updatePackageStatus(packageRoute);
        //1.显示对话框
        showAlertDialog();
    }

    private void showAlertDialog() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_imageview, null);
        ImageView im_dialog_bitmap = dialogView.findViewById(R.id.im_dialog_bitmap);
        im_dialog_bitmap.setImageBitmap(getBitmap());
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setIcon(R.mipmap.ic_launcher).setTitle("提示")
                .setMessage("快递已发货，请保存你的二维码")
                .setView(dialogView)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //退出当前页面
//                        finish();
                        initData();

                    }
                })
                .create()
                .show();
    }

    private Bitmap getBitmap(){
        return CodeUtils.createBarCode(id, BarcodeFormat.CODE_128,800,200);
    }

    /**
     *
     * @return 得到快递下一站的位置
     */

    private String getNextAddress(PackageItem packageItem) {
        String next = "";
        //起始地址
        List<String> start = AppStorage.getRegionThreeName(AppStorage.getRegionName(packageItem.getSourceNode()));
        //目的地址
        List<String> end = AppStorage.getRegionThreeName(AppStorage.getRegionName(packageItem.getTargetNode()));
        //当前地址
        List<String> now = AppStorage.getRegionThreeName(packageItem.getNowAddress());

        Log.i(TAG,start+"/n"+end+"\n"+now);
        if(end == null || start == null || now == null) return "暂无下一站信息";
        if(end.get(0) != null && !end.get(0).equals(now.get(0))){
            //如果当前位置和目的位置不是一个省份
            //判断起始位置和当前位置是不是一个省份
            //如果不是就返回end.get(0)
            if(start.get(0) != null && start.get(0).equals(now.get(0))){
                //河南郑州中原，河南开封龙庭=河南
                //河南郑州中原，河南郑州金水=河南郑州
                for(int i = 0;i<3;i++){
                    if(start.get(i).equals(now.get(i))){
                        next += start.get(i);
                    }else{
                        return next;
                    }
                }
                return start.get(0)+start.get(1);
            }else{
                return end.get(0);
            }
        }

        //河南郑州中原，河南开封龙庭=河南郑州
        //河南郑州中原，河南郑州金水=河南郑州中原
        //河南郑州中原，河北。。。 = 河南，
        //先和目的地址进行比较，首先目的地址和当前地址一定不一样
        for(int i = 0;i<3;i++){
            if(end.get(i)!=null && end.get(i).equals(now.get(i))){
                next += end.get(i);
            }else{
                next += end.get(i);
                return next;
            }
        }
        return next;
    }

}